package com.lhsy.djcloud.controller;

import cn.hutool.core.util.StrUtil;
import com.lhsy.djcloud.common.ReturnT;
import com.lhsy.djcloud.common.SpringContextUtil;
import com.lhsy.djcloud.config.NonStaticResourceHttpRequestHandler;
import com.lhsy.djcloud.config.UploadProjectProperties;
import com.lhsy.djcloud.entity.Upload;
import com.lhsy.djcloud.service.UploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;

/**
 * @author wzw
 * @Date: 2020/10/13 2018/11/02
 */
@RestController
@RequestMapping("/down")
@Api(value = "Server-API",tags = "文件下载接口")
@Slf4j
@AllArgsConstructor
public class DownController extends BaseController{

    @Autowired
    private UploadService uploadService;

    /**
     * 上传web格式图片
     */
    @GetMapping("/file")
    @ApiOperation(value = "文件下载")
    public ReturnT uploadImage(@RequestParam String sha1, HttpServletRequest request,HttpServletResponse response) {
        UploadProjectProperties uploadProjectProperties = SpringContextUtil.getBean(UploadProjectProperties.class);
        String filePath = uploadProjectProperties.getProjectPath();
        System.out.println(filePath);
        Upload bySha1 = uploadService.getBySha1(sha1);
        if (Objects.isNull(bySha1)){
            return ReturnT.FAIL(ReturnT.FAIL_CODE,"文件不存在");
        }
        String fileName = bySha1.getPath();
        File file = new File(filePath+File.separator+fileName);
        // 如果文件名存在，则进行下载
        if (file.exists()) {
            // 配置文件下载
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            try {
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            // 实现文件下载
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("Download the song successfully!");
                return null;
            }
            catch (Exception e) {
                System.out.println("Download the song failed!");
                return null;
            }
            finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                return null;
            }
        }
        return ReturnT.FAIL(ReturnT.FAIL_CODE,"文件不存在");
    }


    private final NonStaticResourceHttpRequestHandler nonStaticResourceHttpRequestHandler;

    /**
     * 预览视频文件, 支持 byte-range 请求
     */
    @GetMapping("/video")
    public ReturnT videoPreview(@RequestParam String sha1,HttpServletRequest request, HttpServletResponse response) throws Exception {
        UploadProjectProperties uploadProjectProperties = SpringContextUtil.getBean(UploadProjectProperties.class);
        String filePath = uploadProjectProperties.getProjectPath();
        System.out.println(filePath);
        Upload bySha1 = uploadService.getBySha1(sha1);
        if (Objects.isNull(bySha1)){
            return ReturnT.FAIL(ReturnT.FAIL_CODE,"文件不存在");
        }
        String fileName = bySha1.getPath();
        Path path = Paths.get(filePath+File.separator+fileName);
        if (Files.exists(path)) {
            String mimeType = Files.probeContentType(path);
            if (!StrUtil.isEmpty(mimeType)) {
                response.setContentType(mimeType);
            }
            request.setAttribute(NonStaticResourceHttpRequestHandler.ATTR_FILE, path);
            nonStaticResourceHttpRequestHandler.handleRequest(request, response);
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        }

        return null;
    }
}
